package org.example.config;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.dao.PermissionDao;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import reactor.core.publisher.Flux;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@Slf4j
public class GatewayConfig {
    @Resource
    PermissionDao permissionDao;

   // @Primary    //提升bean的优先级
    @Bean(name="definitionLocator")    //避免与Gateway内置的bean同名
    public RouteDefinitionLocator routeDefinitionLocator(){
        return () -> {
            // 从数据库查询路由配置
            // Permission -> RouteDefinition
            return Flux.fromIterable(permissionDao.findAllRoutes().stream()
                    .map(perm->{
                RouteDefinition rd = new RouteDefinition();
                rd.setId(perm.getServiceName());
                rd.setUri(URI.create("lb://" + perm.getServiceName()));
                rd.setPredicates(List.of(new PredicateDefinition("Path="+perm.getUri())));
                log.info("添加用户信息");
                return rd;
            }).collect(Collectors.toList()));
        };
    }



    @Bean
    public org.springframework.security.crypto.password.PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
